<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>   
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>  
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>  
<%@ taglib uri="http://shiro.apache.org/tags" prefix="shiro" %>     
<c:set var="ctx" value="${pageContext.request.contextPath}"/> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<jsp:include page="../include.jsp"/>
<script type="text/javascript">
	var dataGrid;
	$(function() {
		//setHeight();
		initTree();
		dataGrid = $('#dg').datagrid({
			iconCls:'icon-user',
			title:'用户信息',
			url:'${ctx}/user/listUsers',
			nowrap:true,
			striped:true,
			idField:'userId',
			pagination:true,
			fit:true,
			//fitColumns:true,
			frozenColumns:[[
				{field:'userId',checkbox :true}
			]],
			sortName:'USER_NAME',
			sortOrder:'desc',
			rownumbers: true, //是否加行号 
			columns:[[
				 {field:'userName',title:'用户名',width:120,align:'left'},
	    		 {field:'realName',title:'姓名',width:130,align:'left'},	    		
	    		 {field:'deptName',title:'所属单位',width:150,align:'left',formatter:formatterOrg},
	    		 {field:'roles',title:'操作角色',width:220,align:'left',formatter:formatterRoles},
	    		 {field:'dataRoles',title:'数据角色',width:220,align:'left',formatter:formatterDataRoles}	
			]],
			toolbar : '#toolbar',
			onHeaderContextMenu: function(e, field){
                e.preventDefault();
                $(this).datagrid('columnMenu').menu('show', {
                    left:e.pageX,
                    top:e.pageY
                });
            },
			onLoadSuccess: function(data){
				 $("#dg").datagrid('tooltip',['roles','dataRoles']);
			},
		}).datagrid('columnMoving');
		
	});
	
	function add() {
		var orgId = $("#orgId").val();
		//alert(orgId);
		parent.$.modalDialog({
			title:'添加用户',
			iconCls:'icon-user-add',
			href:'${ctx}/user/toUserAdd?orgId='+orgId,
			width:'60%',
			height:'90%',
			resizable:true,
			collapsible:true,
			maximizable:true,
			buttons:[{
				text:'提交',
				toggle:true,
				iconCls:'icon-ok',
				handler:function() {
					parent.$.modalDialog.openner_dataGrid = dataGrid;//因为添加成功之后，需要刷新这个dataGrid，所以先预定义好
					var f = parent.$.modalDialog.handler.find('#form');
					f.submit();
				}
			},{
				text:'取消',
				iconCls:'icon-cancel',
				handler:function() {
					parent.$.messager.confirm('系统提示', '确定要关闭当前窗口?', function(r){
		                if (r){
		                	parent.$.modalDialog.handler.dialog('close');
		                }
		            });					
				}
			}]
		});
	}
	
	function doSearch(){
		var params=$('#queryForm').serializeObject();
		$('#dg').datagrid('load',params);  
	}
	
	function doClear(){
		$('#queryForm').form("clear");
		//取消树选择
		$('#tt').find('.tree-node-selected').removeClass('tree-node-selected');
	}
	
	
	function batchDel(){
		var rows = dataGrid.datagrid('getChecked');
		var ids = [];
		if (rows.length > 0) {
			parent.$.messager.confirm('确认', '您是否要删除当前选中的项目？', function(b){ if(b){										
					$.each(rows,function(n,row) {			           
			            ids.push(row.userId);
			        });					
					$.ajax({
	   					type: "POST",
	   					url: '${ctx}/user/deleteUser',
	   					dataType:"json",
	   					data:{
	   						ids : ids.join(',')
	   					},
	   					success: function(result) {	   						
	     					if(result.success == true) {	     						
								parent.$.messager.alert('提示', result.msg, 'info');								
								dataGrid.datagrid('uncheckAll').datagrid('unselectAll').datagrid('clearSelections');
								dataGrid.datagrid('load');
	     					} else {
	     						parent.$.messager.alert('错误', result.msg, 'error');		     						
	     					}	     				
		   				}
					});
					parent.$.messager.progress('close');	
				}
			});
		} else {
			parent.$.messager.alert('系统提示', '请勾选要删除的记录！', 'warning');
		}
	}
	
	
	function udpate(id){
		if (typeof(id) == 'undefined') {
			var rows = dataGrid.datagrid('getSelections');				
			if(rows.length != 1){
				parent.$.messager.alert('系统提示', '请选择一条记录！', 'warning');
				return;
			}
			id = rows[0].userId;	
		} else {
			dataGrid.datagrid('unselectAll').datagrid('uncheckAll');
		}
		parent.$.modalDialog({
			title:'编辑用户',
			iconCls:'icon-user-edit',
			href:'${ctx}/user/toUserAdd?userId=' + id,
			width:'60%',
			height:'90%',
			resizable:true,
			collapsible:true,
			maximizable:true,
			buttons:[{
				text:'修改',
				iconCls:'icon-ok',
				handler : function() {
					parent.$.modalDialog.openner_dataGrid = dataGrid;//因为添加成功之后，需要刷新这个dataGrid，所以先预定义好
					var f = parent.$.modalDialog.handler.find('#form');
					f.submit();
				}
			},{
				text:'取消',
				iconCls:'icon-cancel',
				handler:function(){
					parent.$.messager.confirm('系统提示', '确定要关闭当前窗口?', function(r){
		                if(r){
		                	parent.$.modalDialog.handler.dialog('close');
		                }
		            });					
				}
			}]
		});
	}
	
	function restRestUserPwd(id){
		if (typeof(id) == 'undefined') {
			var rows = dataGrid.datagrid('getSelections');				
			if(rows.length != 1){
				parent.$.messager.alert('系统提示', '请选择一条记录！', 'warning');
				return;
			}
			id = rows[0].userId;	
		} else {
			dataGrid.datagrid('unselectAll').datagrid('uncheckAll');
		}
		 parent.$.modalDialog({
				title:'修改用户密码',
				iconCls:'icon-user-edit',
				href:'${ctx}/user/toRestUserPwd?userId='+id,
				width:'30%',
				height:'45%',
				resizable:false,
				collapsible:false,
				maximizable:false,
				noProgressable:true,
				buttons:[{
					text:'修改',
					iconCls:'icon-ok',
					handler : function() {
						parent.$.modalDialog.openner_dataGrid = dataGrid;//因为添加成功之后，需要刷新这个dataGrid，所以先预定义好
						var f = parent.$.modalDialog.handler.find('#form');
						f.submit();
					}
				},{
					text:'取消',
					iconCls:'icon-cancel',
					handler:function(){
						parent.$.messager.confirm('系统提示', '确定要关闭当前窗口?', function(r){
			                if(r){
			                	parent.$.modalDialog.handler.dialog('close');
			                }
			            });					
					}
				}]
			});
		
	}
	
	//数据权限页面
	function dataAuth(id){
		if (typeof(id) == 'undefined') {
			var rows = dataGrid.datagrid('getSelections');				
			if(rows.length != 1){
				parent.$.messager.alert('系统提示', '请选择一条记录！', 'warning');
				return;
			}
			id = rows[0].userId;	
		} else {
			dataGrid.datagrid('unselectAll').datagrid('uncheckAll');
		}
		parent.$.modalDialog({
			title:'数据权限',
			iconCls:'icon-user-edit',
			href:'${ctx}/user/toDataAuthUpd?userId=' + id,
			width:'60%',
			height:'90%',
			resizable:true,
			collapsible:true,
			maximizable:true,
			buttons:[{
				text:'修改',
				iconCls:'icon-ok',
				handler : function() {
					parent.$.modalDialog.openner_dataGrid = dataGrid;//因为添加成功之后，需要刷新这个dataGrid，所以先预定义好
					var f = parent.$.modalDialog.handler.find('#form');
					f.submit();
				}
			},{
				text:'取消',
				iconCls:'icon-cancel',
				handler:function(){
					parent.$.messager.confirm('系统提示', '确定要关闭当前窗口?', function(r){
		                if(r){
		                	parent.$.modalDialog.handler.dialog('close');
		                }
		            });					
				}
			}]
		});
	}
	
	function formatterRoles(value,row,index){
        var roles = '';
        for(var i=0;i<row.roles.length;i++){
             roles += row.roles[i].roleName + ',';
        }
        return roles;
    }
	
	function formatterDataRoles(value,row,index){
        var roles = '';
        for(var i=0;i<row.dataRoles.length;i++){
             roles += row.dataRoles[i].roleName + ',';
        }
        return roles;
    }
	
	
	function formatterOrg(value, row, index){		
		if(row.organization){
			return row.organization.deptName;
		}
		return value;
	}
	
	function setHeight(){
		var c = $('#cc');
		var p = c.layout('panel','north');	// get the north panel
		var oldHeight = p.panel('panel').outerHeight();
		p.panel('resize', {height:'auto'});
		var newHeight = p.panel('panel').outerHeight();
		c.layout('resize',{
			height: (c.height() + newHeight - oldHeight)
		});
	}
	
	function collapse(){
		var node = $('#tt').tree('getSelected');
		$('#tt').tree('collapse',node.target);
	}
	function expand(){
		var node = $('#tt').tree('getSelected');
		$('#tt').tree('expand',node.target);
	}
	
	function collapseAll(){
		var node = $('#tt').tree('getSelected');
		$('#tt').tree('collapseAll',node.target);
	}
	function expandAll(){
		var node = $('#tt').tree('getSelected');
		$('#tt').tree('expandAll',node.target);
	}
	
	function initTree(){
		orgTree = $('#tt').tree({ 
	       lines:true,
	       checkbox: false,  
	       url: '${ctx}/org/getAllOrganization',  
	       formatter:function(node){
	    	   if(node.children.length){
		    	   return node.text +' <span style=\'color:blue\'>{' + node.children.length + '}</span>';
	    	   }
	    	   return node.text;
		   	},
		   	onContextMenu: function(e,node){
				e.preventDefault();
				$(this).tree('select',node.target);
				$('#mm').menu('show',{
					left: e.pageX,
					top: e.pageY
				});
			},
			onClick: function(node){
				loadUsers(node);
				//支持点击展开/折叠
            	$("#tt").tree(node.state === 'closed' ? 'expand' : 'collapse', node.target);
			},
			onLoadSuccess:function(node, data){
				if(data){				
					$(data).each(function(index, value) {
						if (this.state == 'open') {
							$('#tt').tree('collapseAll');
						}
					});
					expandRoot();
				} 
			}
	    });
	}
	
	//展开最顶层的 根节点
	function expandRoot(){
		//湖北中烟组织机构数据根节点ID值
		var rootId = '${orgRootId}';
		var root = orgTree.tree('find', rootId);
		orgTree.tree('expand', root.target);
	}
	
	function loadUsers(node){
		//$('#deptCode').val(node.attributes.deptCode);
		$('#orgId').val(node.id);
		doSearch(); 
	}
</script>
</head>
<body>
	<div id="cc" class="easyui-layout" data-options="fit:true">
		<div data-options="region:'west',split:false,title:''" style="width:25%;padding:10px;">
	    	<ul id="tt"></ul> 
	    </div>
		<div data-options="region:'center',border:false">
			<div class="easyui-layout" data-options="fit:true">
				<div data-options="region:'north',border:false" style="padding-top:10px;padding-left:5px">	        
			        <form id="queryForm" method="post">					        	
			        	<input id="orgId" type="hidden" name="orgId" type="text" />
						<input class="easyui-textbox" name="userName" label="用户名:"  labelWidth="70px" labelAlign="right" labelPosition="left" data-options="" style="width:25%;height:24px;">
						<input class="easyui-textbox" name="realName" label="姓名:" labelWidth="50px" labelAlign="right" labelPosition="left" data-options="" style="width:25%;height:24px;">
						<input class="easyui-textbox" name="woNumber" label="工号:" labelWidth="50px" labelAlign="right" labelPosition="left" data-options="" style="width:25%;height:24px;">
						<a onclick="doSearch();" href="javascript:void(0);" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-search'">查询</a>
						<a onclick="doClear();" href="javascript:void(0);" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-reload'">重置</a>				
					</form>
			    </div>
			    <div data-options="region:'center',border:false">
				     <table id="dg"></table>
				</div>
			</div>
		</div>
	</div>
	
	<div id="mm" class="easyui-menu" style="width:120px;">
		<div onclick="collapseAll()" data-options="iconCls:'icon-standard-arrow-in'">折叠所有</div>
		<div onclick="expandAll()" data-options="iconCls:'icon-standard-arrow-out'">展开所有</div>
		<div onclick="expand()" data-options="iconCls:'icon-metro-expand2'">展开当前</div>
		<div onclick="collapse()" data-options="iconCls:'icon-metro-contract2'">折叠当前</div>		
	</div>
		
	<div id="toolbar" style="display: none;">
		<a onclick="add();" href="javascript:void(0);" class="easyui-linkbutton" data-options="toggle:true,plain:true,iconCls:'icon-add'">添加</a>
		<a onclick="udpate();" href="javascript:void(0);" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-edit'">修改</a>
		<a onclick="batchDel();" href="javascript:void(0);" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-remove'">删除</a>
		<a onclick="dataAuth();" href="javascript:void(0);" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-database'">数据角色</a>
		<a onclick="restRestUserPwd();" href="javascript:void(0);" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-lock2'">修改密码</a>
	</div>
</body>
</html>